//
//  UserView.m
//  LoveTravel
//
//  Created by MS on 16-1-26.
//  Copyright (c) 2016年 Lemon. All rights reserved.
//

#import "UserView.h"
#import "UIImageView+WebCache.h"
#import "UIView+Frame.h"

#define uerImgW 34
#define margin 5
@interface UserView ()


@property (weak, nonatomic) IBOutlet UILabel *likeCountView;
@property (weak, nonatomic) IBOutlet UIView *userBaseView;
@property (nonatomic,strong) NSMutableArray * imageVArray;
@property (nonatomic,weak) UIButton * moreBtn;
@end

@implementation UserView

-(void)setProductData:(ProductDetailModel *)productData
{
    _productData  = productData;
    
    self.likeCountView.text = [NSString stringWithFormat:@"%ld",productData.like_count];
    
    
    [_imageVArray removeAllObjects];
    
    for (Product_LikeUsers * user in productData.like_user) {
        
        [self creatImageViewWithUrl:user.avatar];
        
    }
}


-(void)creatImageViewWithUrl:(NSString *)url
{
    UIImageView * imV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, uerImgW, uerImgW)];
    [imV sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"defaultavatar"]];
    imV.layer.cornerRadius = imV.frame.size.width*0.5;
    imV.clipsToBounds = YES;
    [self.userBaseView addSubview:imV];
    [self.imageVArray addObject:imV];
    
}


+(instancetype)userViewWithXib
{
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner: nil options:nil] lastObject];
}


-(void)awakeFromNib
{
    self.imageVArray = [NSMutableArray array];
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"activity_moreP"] forState:UIControlStateNormal];
    [self.userBaseView addSubview:btn];
    btn.adjustsImageWhenDisabled  = NO;
    self.moreBtn = btn;
    [btn addTarget:self action:@selector(ClickMore) forControlEvents:UIControlEventTouchUpInside];
}

-(void)ClickMore
{
    NSLog(@"点击更多");
    
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    [self.userBaseView setNeedsLayout];
    [self.userBaseView layoutIfNeeded];
    
    CGFloat wh = uerImgW;
    CGFloat y = (self.userBaseView.height - wh)*0.5;
    int i = 0;
    
    NSInteger count = self.imageVArray.count;
    NSInteger num = (self.userBaseView.width-(wh+margin+10))/(wh+margin);
    num = MIN(count, num);
    
    for (UIImageView * imgV in self.imageVArray) {
        
        if (i<num) {
            CGFloat x = 10+i*(wh+margin);
            imgV.frame = CGRectMake(x, y, wh, wh);
            if (i==num-1) {
                _moreBtn.frame = CGRectMake(10+(i+1)*(wh+margin), y, wh, wh);
            }
        }
        else{
            imgV.frame = CGRectZero;
        }
        
        i++;
    }
    
    if (count==0) {
         _moreBtn.frame = CGRectMake(10, y, wh, wh);
    }
    
}

@end
